import axios from 'axios'

const baseUrl = import.meta.env.VITE_API_URL
const timeout = 10 * 1000

const apiClient = axios.create({
  baseURL: baseUrl,
  timeout: timeout,
  headers: {
    'Content-Type': 'application/json',
  }
})

apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    
    if (token) {
      config.headers['REQUEST_TOKEN'] = token
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

apiClient.interceptors.response.use(
  (response) => {
    if (!response.data) {
      return Promise.reject('服务器返回数据格式错误')
    }

    const result = response.data

    if (!result.code) {
      return Promise.reject(result.message || '服务器返回数据缺少状态码')
    }

    let code = result.code

    if (code == 1003) {
      window.location.href = '/403'
      return Promise.reject('暂无权限访问')
    }

    if (code == 1004) {
      window.location.href = '/login'
      return Promise.reject('登录过期，请重新登录')
    }

    if (code != 1000) {
      return Promise.reject(result.msg || '服务器异常')
    }

    return result
  },
  (error) => {
    const errorMessage = error?.response?.data?.message || '服务器异常'

    return Promise.reject(errorMessage)
  }
)

export default apiClient
